<?php
require 'vendor/autoload.php';
class Cosup
{
	public static function cosupload($config,$file,$is_water=2) {
		$cosClient = new Qcloud\Cos\Client(array(
		    'region' => $config['region'],
		    'credentials' => array(
		        'appId' => $config['appid'],
		        'secretId' => $config['secretid'],
		        'secretKey' => $config['secretkey'],
		    ),
		));

		// 若初始化 Client 时未填写 appId，则 bucket 的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
		if($file['name']=='blob'||$is_water=='1'){
			$upload_name = 'dome.jpg';
		}else{
			$upload_name = $file['name']; 
		}
		
		$str="0123456789abcdefghijklmnopqrstuvwxyz";
	    $key = "";	
	    for($i=0;$i<4;$i++){
	        $key .= $str{mt_rand(0,32)};
	    }
			
		$key = 'sxkj_offline/'.date('Y-m-d').'/'.uniqid().$key.strrchr($upload_name, '.');
		if($is_water=='1'){
			$local_path = $file;
		}else{
			$local_path = $file["tmp_name"];
		}	
		
		# 上传文件
		## putObject(上传接口，最大支持上传5G文件)
		### 上传内存中的字符串
		try {
			if($file['size']<5342880||$is_water=='1'){
				$result = $cosClient->putObject(array(
			        'Bucket' => $config['bucket'],
			        'Key' => $key,
			        'Body' => fopen($local_path, 'rb')
			    ));
			    
			    $arr = (array)$result;		
				foreach ($arr as $v){
					$array = $v;
				}				    
			    //$res = $array['ObjectURL'];			    
			}else{
				//分片上传视频
				$result = $cosClient->Upload(
			        $bucket = $config['bucket'],
			        $key = $key,
			        $body = fopen($local_path, 'rb')
			    );
			    $arr = (array)$result;		
				foreach ($arr as $v){
					$array = $v;
				}				    
			    //$res = 'http://'.$array['Location'];
			}			
		    return $key;
		}catch (\Exception $e) {
		    return 'error';
		}	
	}			
}



























